﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour {
    public GameObject gameHub;

    public CameraControl cameraControl;
    public GameObject headquarters;
    public PlayerManager playerManager;

    public TankSpawnPoint[] tankSpawns;

    private bool _gameOver;
    private Vector3 _headquartersPosition;

	void Start () {
        _headquartersPosition = headquarters.transform.position;

        SpawnPlayer();
        SpawnFirstWaveEnemy();
        SetCameraTargets();

        StartCoroutine(GameLoop());
	}

    private void SpawnPlayer()
    {
        playerManager.instance = Instantiate(
                playerManager.playerPrefab,
                playerManager.spawnPoint.position,
                playerManager.spawnPoint.rotation
            ) as GameObject;

        playerManager.SetUp();
    }

    private void SpawnFirstWaveEnemy()
    {
        for (int i = 0; i < tankSpawns.Length; i++)
        {
            if(tankSpawns[i].enemyManagers.Count>0)
            {
                EnemyManager em = tankSpawns[i].enemyManagers[0];
                SpawnEnemy(em, tankSpawns[i].spawnPoint);
            }
        }
    }

    private void SpawnEnemy(EnemyManager enemyManager, Transform spawnPoint)
    {
        enemyManager.spawnPoint = spawnPoint;

        enemyManager.instance = Instantiate(
                    enemyManager.enemyPrefab,
                    enemyManager.spawnPoint.position,
                    enemyManager.spawnPoint.rotation
                ) as GameObject;

        enemyManager.SetUp();
    }

    private void SetCameraTargets()
    {
        cameraControl.Targets = new Transform[1];
        cameraControl.Targets[0] = playerManager.instance.transform;
    }

    private IEnumerator GameLoop()
    {
        yield return StartCoroutine(StagePlaying());

        yield return StartCoroutine(StageEnding());
    }

    private IEnumerator StagePlaying()
    {
        while(!EnemyAllClear() && PlayerAlive())
        {
            yield return null;
        }
    }

    private IEnumerator StageEnding()
    {
        Debug.Log("game over, alive="+(playerManager.instance!=null && playerManager.instance.activeSelf));
        playerManager.joyStick.SetActive(false);
        gameHub.SetActive(true);

        if(headquarters==null)
        {
            //TODO 结束后镜头上移一点
            _headquartersPosition.y += 3f;
            cameraControl.MoveTo(_headquartersPosition);
        }

        yield return null;
    }

    private bool PlayerAlive()
    {
        return playerManager.isSetup && playerManager.IsAlive() && headquarters!=null;
    }

    private bool EnemyAllClear()
    {
        int enemyLeft = 0;
        for (int i = 0; i < tankSpawns.Length; i++)
        {
            List<EnemyManager> emList = tankSpawns[i].enemyManagers;

            int lenBeforeRemove = emList.Count;

            if (lenBeforeRemove == 0) continue;

            //从列表中移除已经被干掉的敌人
            while (emList.Count>0 && emList[0].isSetup && emList[0].instance==null)
            {
                emList.Remove(emList[0]);
            }
            int lenAfterRemove = emList.Count;

            //该spawnPoint的enemy被干掉，即数目变少了，则补充一个上场
            if(lenAfterRemove>0 && lenAfterRemove<lenBeforeRemove)
            {
                StartCoroutine(ReSpawnEnemyDelay(emList[0], tankSpawns[i].spawnPoint));
                //SpawnEnemy(emList[0], tankSpawns[i].spawnPoint);
            }

            enemyLeft += lenAfterRemove;

        }
        return enemyLeft == 0;
    }

    private IEnumerator ReSpawnEnemyDelay(EnemyManager enemyManager, Transform spawnPoint)
    {
        yield return new WaitForSeconds(1f);

        SpawnEnemy(enemyManager, spawnPoint);
    }

    public void ReLoadScene()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}
